//
//  KKBLESend.m
//
//  Created by zorro on 2017/11/13.
//  Copyright © 2017年 zorro. All rights reserved.
//

#import "KKBLESend.h"
#import "KKBLEService.h"

@interface KKBLESend ()
@property (nonatomic, strong) NSMutableData *sendImageData;
@property (nonatomic, assign) NSInteger ackCount;
@property (nonatomic, assign) NSInteger more;
@property (nonatomic, assign) BOOL isSendScreenImage;    // 发送图片是否完成的标识2019.05.13
@property (nonatomic, assign) NSInteger currentSendIndex;

@end


@implementation KKBLESend

- (instancetype)init {
    self = [super init];
    if (self) {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(acceptSpeed:) name:@"acceptSpeed" object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(acceptAck:) name:@"acceptAck" object:nil];
        
    }
    return self;
}

// 发送数据
- (void)sendBytes:(UInt8 *)val length:(NSInteger)length block:(KKBLEAcceptBlock)block {
    NSData *data = [[NSData alloc] initWithBytes:val length:length];
    
    LogWrite(nil, ([NSString stringWithFormat:@"%@", data]), nil);
    [self sendData:data block:block];
}

- (void)sendData:(NSData *)data block:(KKBLEAcceptBlock)block {
//    usleep(50000);
    KK_BLEAccept.acceptStatus = block;
    KK_BLEAccept.acceptType   = KKBLEAcceptTypeUnKnown;
    [KK_BLEService senderDataToPeripheral:data];
}

- (void)resetSendCMD {
    [self resetAllupdateData];
    _isSend = NO;
}

// 连接上时发送一大串连续的指令
- (void)sendCMD {
    NSLog(@"sendCMD>>>>>%@  %@ mac >>>>%@", [KK_BLELastDevice getObjectValue], KK_BLEConnect.model.bleUUID,[KK_BLELastDeviceMac getObjectValue]);
    if (KK_BLEConnect.model.bleUUID.length > 0) {
        [KK_BLELastDevice setObjectValue:KK_BLEConnect.model.bleUUID];
    }
    
    NSString *mac = [KK_BLEConnect.model.bleUUID getObjectValue];
    if (mac) {
        [KK_BLELastDeviceMac setObjectValue:KK_BLEConnect.model.bleMAC];
        KK_BLEConnect.model.bleMAC = mac;
        [KK_BLEConnect.model updateToDB];
//        NSLog(@"KK_BLEConnect.model.bleAdvID>>>>%d",KK_BLEConnect.model.bleAdvID);
        
        if (KK_BLEConnect.model.bleAdvID > 0) {
            [mac setIntValue:KK_BLEConnect.model.bleAdvID];
        }
    }
    
    NSLog(@"current >>%@ last>>%@",mac,[SAVELASTDEVICE getObjectValue]);
    NSString *last = [SAVELASTDEVICE getObjectValue];
    if ([mac isEqualToString:last]) {
        
    }
    else
    {
        [SAVELASTDEVICE setObjectValue:mac];
        [SAVEDATAARRAY setObjectValue:nil];
    }
    
    [self resetSendCMD];
    _isSend = NO;
    LogWrite(@"重连刷新", nil, nil);
    if ([KK_BLEModel.chip containsString:@"nrf"]) {
        _bleWaitTime = 0.5;
    } else {
        _bleWaitTime = 1.0;
    }
    [self performSelector:@selector(setting) withObject:nil afterDelay:1.0];
    [self performSelector:@selector(settingEnd) withObject:nil afterDelay:66.0];
    //存在拍照/心率忘记关的时候 连接上先发送停止指令
    [self sendControlTakePhotoState:NO WithUpdateBlock:^(id object, KKBLEAcceptType type) {
    }];
//    [self sendHeartStatus:NO type:1 WithUpdate:^(id object, KKBLEAcceptType type) {
//    }];
//    [self sendHeartStatus:NO type:2 WithUpdate:^(id object, KKBLEAcceptType type) {
//    }];
//    [self sendHeartStatus:NO type:3 WithUpdate:^(id object, KKBLEAcceptType type) {
//    }];

    SN_PublicClass.todaySport.mac = SN_PublicClass.todaySport.mac?SN_PublicClass.todaySport.mac:KK_BLEModel.bleMAC;
    SN_PublicClass.todaySleep.mac = SN_PublicClass.todaySleep.mac?SN_PublicClass.todaySleep.mac:KK_BLEModel.bleMAC;
    SN_PublicClass.todayHeart.mac = SN_PublicClass.todayHeart.mac?SN_PublicClass.todayHeart.mac:KK_BLEModel.bleMAC;
    SN_PublicClass.todayOx.mac =  SN_PublicClass.todayOx.mac?SN_PublicClass.todayOx.mac:KK_BLEModel.bleMAC;
    SN_PublicClass.todayBp.mac = SN_PublicClass.todayBp.mac?SN_PublicClass.todayBp.mac:KK_BLEModel.bleMAC;
}

//同步时间
- (void)setting {
    if (_isSend) {
        //        SHOWMBProgressHUD(@"正在同步请稍后...", nil, nil, NO, 2.0);
        return;
    }
    _isSend = YES;
    
    // 计时开始
    [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"loadStartTime"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    LogWrite(@"开始同步指令", nil, nil);
    
       _fail = YES;
       [self sendSetTimeforDeviceWithUpdate:^(id object, KKBLEAcceptType type) {
           if (type == KKBLEAcceptTypeTime) {
               LogWrite(@"同步时间成功", nil, nil);
               NSLog(@"同步时间成功");
               self.fail = NO;
           }
       }];
//       [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(checkErrorFail) object:nil];
//       [self performSelector:@selector(checkErrorFail) withObject:nil afterDelay:1.0];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(get529) object:nil];
    [self performSelector:@selector(get529) withObject:nil afterDelay:self->_bleWaitTime];
}

- (void)checkErrorFail
{
    if (self.fail) {
        [KK_BLEConnect disConnect];
        LogWrite(nil, @"时间没有同步过来断开蓝牙", nil);
        return;
    }
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(get529) object:nil];
    [self performSelector:@selector(get529) withObject:nil afterDelay:self->_bleWaitTime];
}

//
- (void)get529
{
    [KK_BLESend sendGet529WithBlock:^(id object, KKBLEAcceptType type) {
        
    }];
    LogWrite(@"获取529支持设备", nil, nil);
    NSLog(@"获取529支持设备");
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting0) object:nil];
    [self performSelector:@selector(setting0) withObject:nil afterDelay:_bleWaitTime];
}

- (void)setting0
{
    [KK_BLESend sendSetRealSportDataType:NO block:^(id object, KKBLEAcceptType type) {
        
    }];
    LogWrite(@"🙂同步实时步数间隔成功", nil, nil);
    NSLog(@"🙂同步实时步数间隔成功");
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting4) object:nil];
    [self performSelector:@selector(setting4) withObject:nil afterDelay:_bleWaitTime];
}

// 设置用户信息
- (void)setting4 {
    [self sendUserInfoSettingWithBlock:^(id object, KKBLEAcceptType type) {
        if (type == KKBLEAcceptTypeUserInfo) {

        }
    }];
    LogWrite(@"🙂🙂同步用户信息成功", nil, nil);
    NSLog(@"🙂🙂同步用户信息成功");
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting1) object:nil];
    [self performSelector:@selector(setting1) withObject:nil afterDelay:_bleWaitTime];
}

//同步实时步数
- (void)setting1 {
    [self sendGetRealStepWithUpdate:^(id object, KKBLEAcceptType type) {
//        if (type == KKBLEAcceptTypeRealtimeSport) {
//            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting2) object:nil];
//            [self performSelector:@selector(setting2) withObject:nil afterDelay:_bleWaitTime];
//        }
    }];
    LogWrite(@"🙂🙂🙂同步实时步数成功", nil, nil);
    NSLog(@"🙂🙂🙂同步实时步数成功");
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting2) object:nil];
    [self performSelector:@selector(setting2) withObject:nil afterDelay:0.5];
}

// 同步Mac地址
- (void)setting2 {
    [self sendGetDeviceMacAddress:^(id object, KKBLEAcceptType type) {
        if (type == KKBLEAcceptTypeDevideMAC) {
        }
    }];
    LogWrite(@"🙂🙂🙂🙂同步mac地址成功", nil, nil);
    NSLog(@"🙂🙂🙂🙂同步mac地址成功");
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting3) object:nil];
    [self performSelector:@selector(setting3) withObject:nil afterDelay:_bleWaitTime];
}

//获取设备信息
- (void)setting3 {
    [self sendGetDeviceBasicInfoWithUpdate:^(id object, KKBLEAcceptType type) {
        if (type == KKBLEAcceptTypeDevideInfo) {
            if (KK_BLEModel.bleAdvID !=  0) {
                // 上传设备信息
                dispatch_async(dispatch_get_global_queue(0, 0), ^{
                    [SN_Net updateBleDevice:GetEquipmentInfo Success:^(id object) {
                        
                    } fail:^(id object) {
                        
                    }];
                });
            }
        }
    }];
    LogWrite(@"🙂🙂🙂🙂🙂同步设备信息成功", nil, nil);
    NSLog(@"🙂🙂🙂🙂🙂同步设备信息成功");
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting5) object:nil];
    [self performSelector:@selector(setting5) withObject:nil afterDelay:_bleWaitTime];
}

// 设置提醒
- (void)setting5 {
    [self sendSetLowElecWithUpdateBlock:^(id object, KKBLEAcceptType type) {
        if (type == KKBLEAcceptTypeOther) {

        }
    }];
    LogWrite(@"🙂🙂🙂🙂🙂🙂同步设置提醒成功", nil, nil);
    NSLog(@"🙂🙂🙂🙂🙂🙂同步设置提醒成功");
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting6) object:nil];
    [self performSelector:@selector(setting6) withObject:nil afterDelay:_bleWaitTime];
}

// 推送提醒
- (void)setting6 {
    [self sendSetPushNoticeWithUpdateBlock:^(id object, KKBLEAcceptType type) {
        if (type == KKBLEAcceptTypeNotify) {
            
        }
    }];
    LogWrite(@"🙂🙂🙂🙂🙂🙂🙂同步推送提醒成功", nil, nil);
    NSLog(@"🙂🙂🙂🙂🙂🙂🙂同步推送提醒成功");
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting66) object:nil];
    [self performSelector:@selector(setting66) withObject:nil afterDelay:_bleWaitTime];
}

- (void)setting66
{
    if (SN_USER.isNewAncs) {
        [KK_BLESend sendSetPushNoticeWithUpdateBlocknew:^(id object, KKBLEAcceptType type) {
            
        }];
        LogWrite(@"🙂🙂🙂🙂🙂🙂🙂同步推送提醒成功[新]", nil, nil);
        NSLog(@"🙂🙂🙂🙂🙂🙂🙂同步推送提醒成功[新]");
    }
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting7) object:nil];
    [self performSelector:@selector(setting7) withObject:nil afterDelay:_bleWaitTime];
}

//获取步数大数据
- (void)setting7 {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(sendTemperature2) object:nil];
    [self performSelector:@selector(sendTemperature2) withObject:nil afterDelay:_bleWaitTime];
}

- (void)settingSendTemperature
{
    [self sendTemperatureParamWithDays:2 withBlock:^(id object, KKBLEAcceptType type) {
        
    }];
    [self sendTemperatureParamWithDays:1 withBlock:^(id object, KKBLEAcceptType type) {
        
    }];
    [self sendTemperatureParamWithDays:0 withBlock:^(id object, KKBLEAcceptType type) {
        
    }];
}

//天气 1 2 3 WeatherModel
- (void)sendTemperature
{
    [self sendTemperatureParamWithDays:2 withBlock:^(id object, KKBLEAcceptType type) {
        
    }];
    [self sendTemperatureParamWithDays:1 withBlock:^(id object, KKBLEAcceptType type) {
        
    }];
    [self sendTemperatureParamWithDays:0 withBlock:^(id object, KKBLEAcceptType type) {
        
    }];
}
    
- (void)sendTemperature2
    {
        LogWrite(@"🙂🙂🙂🙂🙂🙂🙂🙂同步天气123成功", nil, nil);
        NSLog(@"🙂🙂🙂🙂🙂🙂🙂🙂同步天气123成功");
        [self settingSendTemperature];
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUpdateBigDatas) object:nil];
        [self performSelector:@selector(delayUpdateBigDatas) withObject:nil afterDelay:_bleWaitTime];
    }

- (void)delayUpdateBigDatas
{
    _isSend = YES;
    [self sendBigStepWithUpdate:^(id object, KKBLEAcceptType type) {
        if (type == KKBLEAcceptTypeDataSport) {

        }
    }];
    LogWrite(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂同步步数大数据成功", nil, nil);
    NSLog(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂同步步数大数据成功");
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting8) object:nil];
    [self performSelector:@selector(setting8) withObject:nil afterDelay:8.0];
}

//获取睡眠大数据
- (void)setting8 {
    [self sendBigSleepWithUpdate:^(id object, KKBLEAcceptType type) {
        if (type == KKBLEAcceptTypeDataSleep) {

        }
    }];
    LogWrite(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂同步睡眠大数据成功", nil, nil);
    NSLog(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂同步睡眠大数据成功");
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting9) object:nil];
    [self performSelector:@selector(setting9) withObject:nil afterDelay:3.0];
}

//获取心率大数据
- (void)setting9 {
    //    NSLog(@"SN_USER.heartFunction>>>>%d",SN_USER.heartFunction);
    //    NSArray *tw64Array = [[NSArray alloc]initWithObjects:@"M2", @"F115", @"115", @"X10", @"X8", @"X64", @"TW64", nil];
    //    [tw64Array containsObject:KK_BLEModel.bleName]；
    //
    //    if (!SN_USER.heartFunction) {
    //        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(settingDrink) object:nil];
    //        [self performSelector:@selector(settingDrink) withObject:nil afterDelay:_bleWaitTime];
    //    } else {
    //        [self sendBigheartWithUpdate:^(id object, KKBLEAcceptType type) {
    //            if (type == KKBLEAcceptTypeDataHeart) {
    //                [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(settingDrink) object:nil];
    //                [self performSelector:@selector(settingDrink) withObject:nil afterDelay:_bleWaitTime];
    //            }
    //        }];
    //    }
    [self sendBigheartWithUpdate:^(id object, KKBLEAcceptType type) {
        if (type == KKBLEAcceptTypeDataHeart) {
            
        }
    }];
    LogWrite(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂同步心率大数据成功", nil, nil);
    NSLog(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂同步心率大数据成功");
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateBigSportHeart) object:nil];
    [self performSelector:@selector(updateBigSportHeart) withObject:nil afterDelay:3.0];
}

- (void)updateBigSportHeart
{
    [self sendSportModeDataWithBlock:^(id object, KKBLEAcceptType type) {
        if (type == BLTAcceptTypeDataSportModeData) {

        }
    }];
    LogWrite(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂同步运动心率成功", nil, nil);
    NSLog(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂同步运动心率成功");
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(settingDrink) object:nil];
    [self performSelector:@selector(settingDrink) withObject:nil afterDelay:3.0];
}


- (void)settingDrink {
    LogWrite(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂同步喝水提醒成功", nil, nil);
    NSLog(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂同步喝水提醒成功");
    [SN_EveryDayModelHelp startDrinkWater];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(settingSedentaryRemind) object:nil];
    [self performSelector:@selector(settingSedentaryRemind) withObject:nil afterDelay:_bleWaitTime];
}

- (void)settingSedentaryRemind {
    LogWrite(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂同步久坐提醒成功", nil, nil);
    NSLog(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂同步久坐提醒成功");
    [SN_EveryDayModelHelp startsedentary];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(settingAlarm) object:nil];
    [self performSelector:@selector(settingAlarm) withObject:nil afterDelay:_bleWaitTime];
}

- (void)settingAlarm {
    LogWrite(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂同步闹钟提醒成功", nil, nil);
    NSLog(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂同步闹钟提醒成功");
    [SN_EveryDayModelHelp startSetAlarmClock];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(settingCalendar) object:nil];
    [self performSelector:@selector(settingCalendar) withObject:nil afterDelay:4.0];
}

- (void)settingCalendar {
    LogWrite(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂同步日程提醒成功", nil, nil);
    NSLog(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂同步日程提醒成功");
    [SN_EveryDayModelHelp startSetCalendar];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(settingIgnoreAll) object:nil];
    [self performSelector:@selector(settingIgnoreAll) withObject:nil afterDelay:4.0];
}

- (void)settingIgnoreAll {
    LogWrite(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂同步勿扰模式", nil, nil);
    NSLog(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂同步勿扰模式");
    [self sendNotDisturbWithBlock:^(id object, KKBLEAcceptType type) {

    }];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(settingEnd) object:nil];
    [self performSelector:@selector(settingEnd) withObject:nil afterDelay:_bleWaitTime];
}

- (void)settingEnd {
    LogWrite(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂蓝牙同步设置结束", nil, nil);
    NSLog(@"🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂🙂蓝牙同步设置结束>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
    SN_USER.lastUpdateTime = [[NSDate date]dateToString];
    [SN_USER updateToDB];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(settingEnd) object:nil];
    _isSend = NO;
    
    // 回调至首页下拉刷新完成
    if (self.updateDataEndBlock) {
        self.updateDataEndBlock();
    }
    
    if (ISOPENFRIENDFUNCTION) {
        [SN_Net friendUploadDataSuccess:^(id object) {
            
        } fail:^(id object) {
            
        }];
    }
    
    NSDate *loadStartTime = [[NSUserDefaults standardUserDefaults] objectForKey:@"loadStartTime"];
    if (loadStartTime) {
        NSInteger second = [NSDate intervalSecondsWithSmallDate:loadStartTime bigDate:[NSDate date]];
        NSLog(@"全部指令发送完成所需时间秒数:%ld",(long)second);
        NSString *secondStr = [NSString stringWithFormat:@"%ld",(long)second];
        LogWrite(@"全部指令发送完成所需时间秒数", secondStr, nil);
        
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"loadStartTime"];
    }
}

// 升级
- (void)sendUpdateFirmwareWithUpdateBlock:(KKBLEAcceptBlock)block {
    UInt8 val[3] = {0x05, 0x00, 0x02};
    
    LogWrite(@"升级", nil, nil);
    [self sendBytes:val length:3 block:block];
}

/*******************************X9协议**************************/
//设置时间
- (void) sendSetTimeforDeviceWithUpdate:(KKBLEAcceptBlock)block {
    NSDate *date      = [NSDate date];
    int    i          = date.year;
    int    yearHeight = 0;
    int    yearLow    = 0;
    
    yearHeight = i / 256;
    yearLow    = i - yearHeight *256;
    UInt8 val[10] = {0x05, 0x02, 0x01, yearHeight, yearLow, date.month, date.day, date.hour, date.minute, date.second};
    LogWrite(@"设置时间", nil, nil);
    NSData *data2 = [[NSData alloc] initWithBytes:val length:10];
    NSString *content = [NSString stringWithFormat:@"%@", data2];
    NSLog(@"设置时间指令:%@",content);
    [self sendBytes:val length:10 block:block];
//    NSData *data = [[NSData alloc] initWithBytes:val length:10];
////    KK_BLEAccept.acceptTypeTimeBlock = [block copy];
//    KK_BLEAccept.acceptType   = KKBLEAcceptTypeUnKnown;
//    [KK_BLEService senderDataToPeripheral:data];
}

//获取设备mac地址
- (void)sendGetDeviceMacAddress:(KKBLEAcceptBlock)block {
    UInt8 val[3] = {0x05, 0x01, 0x01};
    NSData *data2 = [[NSData alloc] initWithBytes:val length:3];
    NSString *content = [NSString stringWithFormat:@"%@", data2];
    NSLog(@"获取设备mac地址指令:%@",content);
    LogWrite(@"获取mac地址", content, nil);
    
    [self sendBytes:val length:3 block:block];
}

//获取设备基本信息
- (void)sendGetDeviceBasicInfoWithUpdate:(KKBLEAcceptBlock)block {
    UInt8 val[3] = {0x05, 0x01, 0x02};
    NSData *data2 = [[NSData alloc] initWithBytes:val length:3];
    NSString *content = [NSString stringWithFormat:@"%@", data2];
    NSLog(@"获取设备基本信息指令:%@",content);
    LogWrite(@"获取设备基本信息", content, nil);
    [self sendBytes:val length:3 block:block];
}

// 系统配对
- (void)sendUserPairWithBlock:(KKBLEAcceptBlock)block {
    int ios   = 0x00; // 00 表示ios  //01 表示安卓 // 02 表示已经配对了
    int step1 = 0;
    int step2 = 0;
    int step3 = 0;
    int step4 = 0;
    
    step4 = SN_USER.target_step %256;
    step3 = SN_USER.target_step /256;
    step2 = SN_USER.target_step /256/256;
    step1 = SN_USER.target_step /256/256/256;
    UInt8 val[17] = {0x05, 0x02, 0x02, SN_USER.gender, SN_USER.age, SN_USER.height,
        (int)SN_USER.weight, SN_USER.lanuage, SN_USER.is12Time, SN_USER.isMetricSystem, ios, SN_USER.hand, SN_USER.temperatureSet, step1, step2, step3, step4};
    LogWrite(@"设置用户信息", nil, nil);
    [self sendBytes:val length:17 block:block];
}

// 用户信息
- (void)sendUserInfoSettingWithBlock:(KKBLEAcceptBlock)block {
    int ios = 0x00;  // 00 表示ios  //01 表示安卓 // 02 表示已经配对了

    if (KK_BLEConnect.isFoundPair) {
        ios = 0x02;   // 00 表示ios  //01 表示安卓
    } else {
        ios = 0x00;   // 00 表示ios  //01 表示安卓
    }
    int step1 = 0;
    int step2 = 0;
    int step3 = 0;
    int step4 = 0;
    step4 = SN_USER.target_step %256;
    step3 = SN_USER.target_step /256;
    step2 = SN_USER.target_step /256/256;
    step1 = SN_USER.target_step /256/256/256;
//    NSString *formatStringForHours = [NSDateFormatter dateFormatFromTemplate:@"j" options:0 locale:[NSLocale currentLocale]];
//    NSRange  containsA             = [formatStringForHours rangeOfString:@"a"];
//    BOOL     hasAMPM               = containsA.location != NSNotFound;
    //    SN_USER.is12Time TURE为12小时制，否则为24小时制
    NSArray  *appLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
    NSString *languageName = [appLanguages objectAtIndex:0];

    
    int      lanuage         = SN_USER.lanuage;
    if (SN_USER.showLanuage == YES) {
        NSArray *lanuageArray = SN_USER.lanuageArray;
        lanuage = [[lanuageArray firstObject]intValue];
        //模拟手环配置的语言
//        lanuageArray = @[@"01",@"00",@"09",@"10"];
        
        NSLog(@"🙂🙂🙂手环后台配置的默认语言>>>%d 1:%@ 2:%@",lanuage,lanuageArray,SN_USER.lanuageArray);
        
        NSMutableArray *newArray = [NSMutableArray array];
        for (int i = 0; i < lanuageArray.count; i ++ ) {
            [newArray addObject:[NSString stringWithFormat:@"%d",[lanuageArray[i] intValue]]];
        }

        NSString *current = [NSString stringWithFormat:@"%d",SN_USER.lanuage2];
        if ([newArray containsObject:current]) {
            lanuage = current.intValue;
        }
//        NSLog(@"默认>>>%@",lanuageArray);
//        NSLog(@"当前>>>%@",current);
//        NSLog(@"111111111 SN_USER.lanuage>>>%d",lanuage);
        NSString *info = [NSString stringWithFormat:@"🙂🙂🙂系统语言:%@ 手环后台配置:%@ 当前语言:%@ 匹配后台语言:%d",languageName,lanuageArray,current,lanuage];
        NSLog(@"%@",info);
        LogWrite(nil, info, nil);
    }
    else
    {
        lanuage = SN_USER.lanuage;
        NSLog(@"222222222 SN_USER.lanuage>>>%d",lanuage);
    }
    
    UInt8 val[17] = {0x05, 0x02, 0x02, SN_USER.gender, SN_USER.age, SN_USER.height,
        (int)SN_USER.weight, lanuage, SN_USER.is12Time, SN_USER.isMetricSystem, ios, SN_USER.hand, SN_USER.temperatureSet, step1, step2, step3, step4};
    LogWrite(@"设置用户信息", nil, nil);
    NSData *data2 = [[NSData alloc] initWithBytes:val length:17];
    NSString *content = [NSString stringWithFormat:@"%@", data2];
    NSLog(@"设置用户信息指令:%@",content);
    [self sendBytes:val length:17 block:block];
}

//免打扰
- (void)sendNotDisturbWithBlock:(KKBLEAcceptBlock)block {
    UInt8 val[8] = {0x05, 0x02, 0x0B, SN_USER.isOpen, SN_USER.startH, SN_USER.startM, SN_USER.endH, SN_USER.endM};
    
    LogWrite(@"免打扰设置", nil, nil);
    NSData *data = [[NSData alloc] initWithBytes:val length:9];
    [KK_BLEService senderDataToPeripheral:data];
}

//实时步数
- (void)sendGetRealStepWithUpdate:(KKBLEAcceptBlock)block {
    UInt8 val[3] = {0x05, 0x07, 0x01};
    
    LogWrite(@"获取实时步数", nil, nil);
    [self sendBytes:val length:3 block:block];
}

//记步大数据
- (void)sendBigStepWithUpdate:(KKBLEAcceptBlock)block {
    UInt8 val[3] = {0x05, 0x07, 0x03};
    
    LogWrite(@"获取计步大数据", nil, nil);
    [self sendBytes:val length:3 block:block];
}

//睡眠大数据
- (void)sendBigSleepWithUpdate:(KKBLEAcceptBlock)block {
    UInt8 val[3] = {0x05, 0x07, 0x04};
    
    LogWrite(@"获取睡眠大数据", nil, nil);
    [self sendBytes:val length:3 block:block];
}

//心率大数据 2017 10 26
- (void)sendBigheartWithUpdate:(KKBLEAcceptBlock)block {
    UInt8 val[3] = {0x05, 0x07, 0x07};
    
    LogWrite(@"获取心率大数据", nil, nil);
    [self sendBytes:val length:3 block:block];
}

// 拍照控制
- (void)sendControlTakePhotoState:(BOOL)type WithUpdateBlock:(KKBLEAcceptBlock)block {
    UInt8 val[4] = {0x05, 0x05, 0x02, type};
    
    LogWrite(@"拍照", nil, nil);
    [self sendBytes:val length:4 block:block];
    NSLog(@"发送拍照指令>>>>%i",type);
}

// 找手环
- (void)sendSetFindBle:(BOOL)Find withUpdateBlock:(KKBLEAcceptBlock)block {
    UInt8 val[4] = {0};
    val[0] = 0x05;
    val[1] = 0x05;
    val[2] = 0x03;
    val[3] = Find;
    LogWrite(@"找手环", nil, nil);
    NSData *data = [[NSData alloc] initWithBytes:val length:4];
    [KK_BLEService senderDataToPeripheral:data];
}

// 心率开关 血氧 血压开关
- (void)sendHeartStatus:(BOOL)status type:(NSInteger)type WithUpdate:(KKBLEAcceptBlock)block {
    if (type == 1) {
        UInt8 val[4] = {0x05, 0x05, 0x01, status};
        [self sendBytes:val length:4 block:block];
        LogWrite(@"手动心率", nil, nil);
    }
    if (type == 2) {
        UInt8 val[4] = {0x05, 0x05, 0x04, status};
        [self sendBytes:val length:4 block:block];
        LogWrite(@"手动血氧", nil, nil);
    }
    if (type == 3) {
        UInt8 val[4] = {0x05, 0x05, 0x05, status};
        [self sendBytes:val length:4 block:block];
        LogWrite(@"手动血压", nil, nil);
    }
}

- (void)sendTemperatureParamWithDays:(NSInteger)days withBlock:(KKBLEAcceptBlock)block
{
    NSArray *sunArr      = @[@"100"];
    NSArray *cloudArr    = @[@"101", @"102", @"103", @"101", @"101", @"201", @"202", @"203", @"204"];
    NSArray *snowArr     = @[@"400", @"401", @"402", @"403", @"404", @"405", @"406", @"407", ];
    NSArray *overcastArr = @[@"104", @"200", @"205", @"206", @"207", @"208", @"210", @"500", @"501", @"502", @"503", @"504", @"507", @"508"];
    NSArray *rainArr     = @[@"209", @"211", @"212", @"213", @"300", @"301", @"302", @"304", @"305", @"306", @"307", @"308", @"309", @"310", @"311", @"312", @"313"];
    NSArray *nonArr      = @[@"900", @"901", @"902"];
    int     type         = 0x00;
    
    SNWeatherModel *model = [SN_USER.weatherArray objectAtIndex:days];
    if ([sunArr containsObject:model.weatherCode]) {
        type = 0x01;
    } else if ([cloudArr containsObject:model.weatherCode]) {
        type = 0x02;
    } else if ([snowArr containsObject:model.weatherCode]) {
        type = 0x18;
    } else if ([overcastArr containsObject:model.weatherCode]) {
        type = 0x03;
    } else if ([rainArr containsObject:model.weatherCode]) {
        type = 0x07;
    } else if ([nonArr containsObject:model.weatherCode]) {
        type = 0x00;
    }
    int   maxTem     = [model.maxTem intValue];
    int   minTem     = [model.minTem intValue];
    int   currentTem = [model.tem intValue];
    UInt8 val[16]    = {0x05, 0x02, 0x0E, type, 0x00, 0x00, currentTem, 0x00, maxTem, 0x00, minTem,0x00,0x00,0x00,0x00,days};
    NSData *data = [[NSData alloc] initWithBytes:val length:16];
    [KK_BLEService senderDataToPeripheral:data];
    
//    NSLog(@"天气序号:%ld,指令:%@",(long)days,[NSString stringWithFormat:@"%@", data]);
    NSString *order = [NSString stringWithFormat:@"天气序号:%ld",(long)days];
    LogWrite(order, ([NSString stringWithFormat:@"%@", data]), nil);
}

// 发送低电 抬腕 防丢 心率检测 翻腕切屏
- (void)sendSetLowElecWithUpdateBlock:(KKBLEAcceptBlock)block {
    int lost = SN_USER.lostNotice;
    if (SN_USER.showBleLost == 0) {
        lost = 0;
    }
    UInt8 val[8] = {0x05, 0x02, 0x0A, SN_USER.lowElecNotice, SN_USER.liftNotice, lost, SN_USER.heartAutoCheck, SN_USER.changeScreen};
    
    LogWrite(@"低电 抬腕 防丢 心率检测 翻腕切屏", nil, nil);
    [self sendBytes:val length:8 block:block];
}

// 消息推送 电话 短信
- (void)sendSetPushNoticeWithUpdateBlock:(KKBLEAcceptBlock)block {
    int MessageNotice = 0;
    if (SN_USER.ancsNotice) {
        if (KK_BLEModel.bleCustomerID == 0) {
            MessageNotice = 255; // 旧版为 bit 0 ~ bit 5 对应的开关
        } else {
            MessageNotice = 1;   // 新版只有一个总开关1
        }
    } else {
        MessageNotice = 0;
    }
    NSLog(@"MessageNotice>>>>>>%d  SN_USER.ancsNotice >>>%i",MessageNotice,SN_USER.ancsNotice);
    if (SN_USER.isNewAncs) {
        BOOL newMessageNotice = NO;
        if (SN_USER.Instagram || SN_USER.Emails || SN_USER.Facebook || SN_USER.Wechat ||SN_USER.Line || SN_USER.Weibo ||SN_USER.Linkin ||SN_USER.QQ ||SN_USER.WhatsApp ||SN_USER.Viber ||SN_USER.Others) {
            newMessageNotice = YES;
        }
        UInt8 val[6] = {0x05, 0x02, 0x09, SN_USER.phoneNotice, SN_USER.smsNotice, newMessageNotice};
        LogWrite(@"消息推送 电话 短信", nil, nil);
        [self sendBytes:val length:6 block:block];
    }
    else
    {
        UInt8 val[6] = {0x05, 0x02, 0x09, SN_USER.phoneNotice, SN_USER.smsNotice, MessageNotice};
        LogWrite(@"消息推送 电话 短信", nil, nil);
        [self sendBytes:val length:6 block:block];
    }
}

// 新增推送
- (void)sendSetPushNoticeWithUpdateBlocknew:(KKBLEAcceptBlock)block
{
    UInt8 val[14] = {0x05, 0x02, 0x1D, SN_USER.Others, SN_USER.Emails,SN_USER.Facebook,SN_USER.Wechat,SN_USER.Line,SN_USER.Weibo,SN_USER.Linkin,SN_USER.QQ,SN_USER.WhatsApp,SN_USER.Viber,SN_USER.Instagram};
    NSLog(@"消息推送 5.29");
    LogWrite(@"消息推送 5.29", nil, nil);
    NSLog(@"SN_USER.Others>>>%i",SN_USER.Others);
    NSLog(@"SN_USER.Viber>>>%i",SN_USER.Viber);
    
    [self sendBytes:val length:14 block:block];
}

- (void)sendDrinkWithUpdateBlock:(KKBLEAcceptBlock)block {
    UInt8 week = 0;
    week = bitInsertInt(week, 0, SN_USER.drinkSUN);
    week = bitInsertInt(week, 1, SN_USER.drinkMON);
    week = bitInsertInt(week, 2, SN_USER.drinkTUE);
    week = bitInsertInt(week, 3, SN_USER.drinkWED);
    week = bitInsertInt(week, 4, SN_USER.drinkTHU);
    week = bitInsertInt(week, 5, SN_USER.drinkFRI);
    week = bitInsertInt(week, 6, SN_USER.drinkSAT);
    week = bitInsertInt(week, 7, SN_USER.drinkOnce);
    UInt8 val[18] = {0x05, 0x02, 0x06, SN_USER.drinkOpen, week,
        SN_USER.drinkStartHour1, SN_USER.drinkStartMins1, SN_USER.drinkEndHour1, SN_USER.drinkEndMins1,
        SN_USER.drinkStartHour2, SN_USER.drinkStartMins2, SN_USER.drinkEndHour2, SN_USER.drinkEndMins2,
        SN_USER.drinkStartHour3, SN_USER.drinkStartMins3, SN_USER.drinkEndHour3, SN_USER.drinkEndMins3, SN_USER.drinkinterval};
    LogWrite(@"喝水提醒", nil, nil);
    //    NSLog(@"111 >>%d %d - %d %d",SN_USER.drinkStartHour1,SN_USER.drinkStartMins1,SN_USER.drinkEndHour1,SN_USER.drinkEndMins1);
    //    NSLog(@"222 >>%d %d - %d %d",SN_USER.drinkStartHour2,SN_USER.drinkStartMins2,SN_USER.drinkEndHour2,SN_USER.drinkEndMins2);
    //    NSLog(@"333 >>%d %d - %d %d       间隔>>%d",SN_USER.drinkStartHour3,SN_USER.drinkStartMins3,SN_USER.drinkEndHour3,SN_USER.drinkEndMins3,SN_USER.drinkinterval);
    [self sendBytes:val length:18 block:block];
}

- (void)sendSedentaryRemindWithUpdateBlock:(KKBLEAcceptBlock)block {
    UInt8 week = 0;
    
    week = bitInsertInt(week, 0, SN_USER.sedentarySUN);
    week = bitInsertInt(week, 1, SN_USER.sedentaryMON);
    week = bitInsertInt(week, 2, SN_USER.sedentaryTUE);
    week = bitInsertInt(week, 3, SN_USER.sedentaryWED);
    week = bitInsertInt(week, 4, SN_USER.sedentaryTHU);
    week = bitInsertInt(week, 5, SN_USER.sedentaryFRI);
    week = bitInsertInt(week, 6, SN_USER.sedentarySAT);
    week = bitInsertInt(week, 7, SN_USER.sedentaryOnce);
    UInt8 val[18] = {0x05, 0x02, 0x07, SN_USER.sedentaryOpen, week,
        SN_USER.sedentaryStartHour1, SN_USER.sedentaryStartMins1, SN_USER.sedentaryEndHour1, SN_USER.sedentaryEndMins1,
        SN_USER.sedentaryStartHour2, SN_USER.sedentaryStartMins2, SN_USER.sedentaryEndHour2, SN_USER.sedentaryEndMins2,
        SN_USER.sedentaryStartHour3, SN_USER.sedentaryStartMins3, SN_USER.sedentaryEndHour3, SN_USER.sedentaryEndMins3, SN_USER.sedentaryinterval};
    LogWrite(@"久坐提醒", nil, nil);
    //    NSLog(@"aaa >>%d %d - %d %d",SN_USER.sedentaryStartHour1,SN_USER.sedentaryStartMins1,SN_USER.sedentaryEndHour1,SN_USER.sedentaryEndMins1);
    //    NSLog(@"bbb >>%d %d - %d %d",SN_USER.sedentaryStartHour2,SN_USER.sedentaryStartMins2,SN_USER.sedentaryEndHour2,SN_USER.sedentaryEndMins2);
    //    NSLog(@"ccc >>%d %d - %d %d       间隔>>%d",SN_USER.sedentaryStartHour3,SN_USER.sedentaryStartMins3,SN_USER.sedentaryEndHour3,SN_USER.sedentaryEndMins3,SN_USER.sedentaryinterval);
    [self sendBytes:val length:18 block:block];
}

// 闹钟
- (void)sendSetDeviceAlarmClock_KK:(SNAlarmModel *)model
                   withUpdateBlock:(KKBLEAcceptBlock)block {
    UInt8 week = 0;
    week = bitInsertInt(week, 0, model.SUN);
    week = bitInsertInt(week, 1, model.MON);
    week = bitInsertInt(week, 2, model.TUE);
    week = bitInsertInt(week, 3, model.WED);
    week = bitInsertInt(week, 4, model.THU);
    week = bitInsertInt(week, 5, model.FRI);
    week = bitInsertInt(week, 6, model.SAT);
    week = bitInsertInt(week, 7, model.Once);
    NSString *info = [NSString stringWithFormat:@"🙂🙂🙂闹钟开启:%i 星期1:%i 星期2:%i 星期3:%i 星期4:%i 星期5:%i 星期6:%i 星期7:%i 一次:%i",model.open,model.MON,model.TUE,model.WED,model.THU,model.FRI,model.SAT,model.SUN,model.Once];
    NSLog(@"🙂🙂🙂闹钟开启:%i 星期1:%i 星期2:%i 星期3:%i 星期4:%i 星期5:%i 星期6:%i 星期7:%i 一次:%i",model.open,model.MON,model.TUE,model.WED,model.THU,model.FRI,model.SAT,model.SUN,model.Once);
    LogWrite(@"设置闹钟",info, nil);
    UInt8 val[9] = {0x05, 0x02, 0x04, model.orderIndex, model.open, week,
        model.hours, model.mins, model.activeType};
    LogWrite(@"闹钟", nil, nil);
    [self sendBytes:val length:9 block:block];
}

// 日常提醒
- (void)sendSetDeviceCalendarModel:(SNcalendarModel *)model
                   withUpdateBlock:(KKBLEAcceptBlock)block {
    UInt8 val[11] = {0x05, 0x02, 0x05, model.orderIndex, model.open, model.year - 2000, model.month, model.day,
        model.hours, model.mins, model.activeType};
    
    LogWrite(@"日程提醒", nil, nil);
    [self sendBytes:val length:11 block:block];
}

//设备重启
- (void)sendDeviceRebootWithUpdate:(KKBLEAcceptBlock)block {
    UInt8 val[3] = {0x05, 0x00, 0x01};
    
    LogWrite(@"设备重启", nil, nil);
    [self sendBytes:val length:3 block:block];
}

// 主页下拉 刷新 调用
- (void)updateData {
    LogWrite(@"手动下拉刷新", nil, nil);
    if (_isSend) {
        SHOWMBProgressHUD(nil,SN_Text(@"更新中..."), nil, NO, 2.0);
        return;
    }
    _isSend = YES;
    //实时步数
    [self sendGetRealStepWithUpdate:^(id object, KKBLEAcceptType type)
     {
         if (type == KKBLEAcceptTypeRealtimeSport) {

         }
     }];

    LogWrite(@"🙂同步实时步数成功", nil, nil);
    NSLog(@"🙂同步实时步数成功");
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateData1) object:nil];
    [self performSelector:@selector(updateData1) withObject:self afterDelay:_bleWaitTime];
    
    [self performSelector:@selector(updateDataEnd) withObject:self afterDelay:20.0];
}

- (void)updateData1 {
    //记步大数据
    [self sendBigStepWithUpdate:^(id object, KKBLEAcceptType type) {
        if (type == KKBLEAcceptTypeDataSport) {

        }
    }];
    LogWrite(@"🙂同步记步大数据成功", nil, nil);
    NSLog(@"🙂同步记步大数据成功");
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateData2) object:nil];
    [self performSelector:@selector(updateData2) withObject:self afterDelay:8.0];
}

- (void)updateData2 {
    //睡眠大数据
    [self sendBigSleepWithUpdate:^(id object, KKBLEAcceptType type) {
        if (type == KKBLEAcceptTypeDataSleep) {

        }
    }];
    LogWrite(@"🙂同步睡眠大数据成功", nil, nil);
    NSLog(@"🙂同步睡眠大数据成功");
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateData3) object:nil];
    [self performSelector:@selector(updateData3) withObject:self afterDelay:3.0];
}

- (void)updateData3 {
    //心率大数据 2017 10 26
    [self sendBigheartWithUpdate:^(id object, KKBLEAcceptType type) {
        if (type == KKBLEAcceptTypeDataHeart) {

        }
    }];
    LogWrite(@"🙂同步心率大数据成功", nil, nil);
    NSLog(@"🙂同步心率大数据成功");
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateData4) object:nil];
    [self performSelector:@selector(updateData4) withObject:self afterDelay:3.0];
}

- (void)updateData4 {
    // 获取运动模式数据 2019.06.11
    [self sendSportModeDataWithBlock:^(id object, KKBLEAcceptType type) {
        if (type == BLTAcceptTypeDataSportModeData) {

        }
    }];
    LogWrite(@"🙂同步运动心率成功", nil, nil);
    NSLog(@"🙂同步运动心率成功");
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateDataEnd) object:nil];
    [self performSelector:@selector(updateDataEnd) withObject:self afterDelay:3.0];
}

- (void)updateDataEnd {
    SN_USER.lastUpdateTime = [[NSDate date]dateToString];
    NSLog(@"更新大数据同步结束>>>>>>>%@", [[NSDate date]dateToString]);
    [SN_USER updateToDB];
    _isSend = NO;
    
    LogWrite(@"🙂同步结束", nil, nil);
    NSLog(@"🙂同步结束");
    if (ISOPENFRIENDFUNCTION) {
        [SN_Net friendUploadDataSuccess:^(id object) {
            
        } fail:^(id object) {
            
        }];
    }
}

- (void)resetAllupdateData {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(checkErrorFail) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(get529) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting0) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting4) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting1) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting2) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting3) object:nil];
    
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting5) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting6) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting66) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting7) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting8) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(setting9) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(settingDrink) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(settingSedentaryRemind) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(settingAlarm) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(settingCalendar) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(settingIgnoreAll) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateData4) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateData3) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateData1) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateData2) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(updateDataEnd) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(sendTemperature2) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(delayUpdateBigDatas) object:nil];
}

// APP 设置设备是否开启屏保功能 2019.05.15
- (void)sendScreenImageOpenState:(BOOL)open WithBlock:(KKBLEAcceptBlock)block {
    int a;
    if (open) {
        a = 0x01;
    } else {
        a = 0x02;
    }
    UInt8 val[4] = {0x05,0x02,0x12,a};
    [self sendBytes:val length:4 block:block];
}

// 2019.05.18
// 获取设备支持屏保的字体种类及对应分辨率
- (void)sendGetDeviceScreenSaverFontInfo:(KKBLEAcceptBlock)block {
    UInt8 val[3] = {0x05, 0x01, 0x15};
    LogWrite(@"获取设备支持屏保的字体种类及对应分辨率", nil, nil);
    [self sendBytes:val length:3 block:block];
}

// 获取设备屏保信息
//2019.05.16
- (void)sendGetDeviceIsCanSetScreenImage:(KKBLEAcceptBlock)block {
    UInt8 val[3] = {0x05, 0x01, 0x14};
    LogWrite(@"获取设备是否支持屏保图片", nil, nil);
    [self sendBytes:val length:3 block:block];
}

- (void)sendSetIsShowStepSwitchState:(BOOL)open type:(BLTScreenSendType)type fontColor:(UIColor *)color x:(int)x y:(int)y fontType:(int) fontType withBlock:(KKBLEAcceptBlock)block{
    int a;
    if (open) {
        a = 0x01;
    } else {
        a = 0x02;
    }
    
    // 颜色转换
    const CGFloat *components =  CGColorGetComponents([color CGColor]);
    int  r = (int)255*components[0];
    int  g = (int)255*components[1];
    int  b = (int)255*components[2];
    // 转为10进制
    int value = ((r *256) + g) * 256 + b;
    //RGB888ToRGB565
    int    acolor = [RGB565 RGB888ToRGB565:value];
    int colorHeight = acolor >> 8 & 0xff;
    int colorLow = acolor & 0xff;
    
    // 获取字体的相关值
    NSArray *array = [[NSUserDefaults standardUserDefaults] objectForKey:@"FontWidthHight"];
    int fontSize = [array[fontType] intValue];  // 16进制数
    int w = fontSize >> 8 & 0xff;               // 取高位为单个字体的宽  12:00 5个字
    int h = fontSize & 0xff;                    // 取低位为单个字体的高
    
    // 显示位置 拆分高低位传输
    int xHeight = x >> 8 & 0xff;
    int xLow    = x & 0xff;
    
    int yHeight = y >> 8 & 0xff;
    int yLow    = y & 0xff;
    
    int atype = 0;
    if (type == BLTScreenSendTypeTime) {
        // 时间
        atype = 0x13;
        w = 5 *w;
    } else if (type == BLTScreenSendTypeStep) {
        // 步数
        atype = 0x14;
        w = w * 5 + 16;
    } else {
        
    }
    UInt8 val[13] = {0x05, 0x02, atype,a,0x01,w ,h,colorHeight,colorLow,xHeight,xLow,yHeight,yLow};
    [self sendBytes:val length:13 block:block];
}
// 功耗问题 2019.05.23
// APP 设置设备实时运动数据的上传方式
- (void)sendSetRealSportDataType:(BOOL)isBackground block:(KKBLEAcceptBlock)block {
    UInt8 val[4] = {0x05, 0x02, 0x15};
    if (isBackground) {
        val[3] = 0x00; // 2分钟间隔
    } else {
        val[3] = 0x01; // 实时步数
    }
    [self sendBytes:val length:4 block:block];
}

// 2019.06.04 运动模式
- (void)sendSportModeDataWithBlock:(KKBLEAcceptBlock)block {
    UInt8 val[3] = {0x05, 0x07, 0x0B};
    [self sendBytes:val length:3 block:block];
}

// 2019.05.07
//************************图片发送**************************//
// 设置设备是否进入高速传输 1表示开启高速通道 2表示关闭
- (void)sendImageData:(BOOL)isChangeImage WithBlock:(KKBLEAcceptBlock)block
{
    _isSendScreenImage = isChangeImage;
    UInt8 val[4] = {0x05,0x02,0x11,isChangeImage};
    NSData *data = [[NSData alloc] initWithBytes:val length:4];
    [KK_BLEService senderDataToPeripheral:data];
}

// 高速通道是否开启 // 1表示开始传输 2表示关闭
- (void)acceptSpeed:(NSNotification*)info
{
    NSString *object = info.object;
    NSInteger state = [object integerValue];
    if (state == 1 && _isSendScreenImage == YES) {
        // 模拟数据
        NSLog(@"通道开启 开始加载数据");
        NSString *path = KK_BLESend.sendPath;
        _sendImageData = [NSMutableData dataWithContentsOfFile:path];
        [self sendImageDataRun];
    }
    else
    {
        NSLog(@"通道关闭");
    }
    if (_stateBlock) {
        _stateBlock(1);
    }
}

// 初始化数据
- (void)sendImageDataRun
{
    // 计算总打包数（根据这个count轮询等待)
    _ackCount = _sendImageData.length /(512-8);
    _more = _sendImageData.length %(512-8);
    if (_more>0) {
        _ackCount ++;
    }
    _currentSendIndex = 0;
    NSLog(@"总数据长度>>>>%d 总拆分为包:>>>%d 尾包数据长度>>>%d",_sendImageData.length,_ackCount,_more);
    [self sendImageWithCount:_currentSendIndex];// 开始发送第一包
    [[XNProgressHUD shared]dismissWithDelay:1.0];
}

// 模拟接收到校验
- (void)acceptAck:(NSNotification*)info
{
    NSString *object = info.object;
    NSInteger go = [object integerValue];
    //    NSLog(@"_currentSendIndex>>>%d _ack%d",_currentSendIndex,_ackCount);
    if (KK_BLESend.imageSendBlock) {
        KK_BLESend.imageSendBlock(_currentSendIndex, _ackCount);
    }
    
    if (go == 1) {
        if (_currentSendIndex == _ackCount -1) {
            //            NSLog(@"图片发送完成");
            [self sendImageData:NO WithBlock:^(id object, KKBLEAcceptType type) {
                
            }];
            return;
        }
        else
        {
            _currentSendIndex ++;
            //            NSLog(@"校验成功发送下一包>>>");
            //            SHOWMBProgressHUD(@"校验成功", nil, nil, NO, 1.0);
        }
    }
    else
    {
        //        NSString *error = [NSString stringWithFormat:@"第%d包校验失败",_currentSendIndex];
        //        SHOWMBProgressHUD(error, nil, nil, NO, 1.0);
        //        NSLog(@"校验失败重发>>>");
    }
    
    [self sendImageWithCount:_currentSendIndex];
}

// 根据序号发送包
- (void)sendImageWithCount:(NSInteger)current
{
    NSInteger lastLength = _sendImageData.length - (_currentSendIndex)*504;
    int length = 0;
    if (lastLength >504) {
        length = 504;
    }
    else
    {
        length = lastLength;
    }
    
    NSData *bigData = [_sendImageData subdataWithRange:NSMakeRange((_currentSendIndex)*504,length)];
    //    NSLog(@"序号>>>%d 包长度>>>%d",_currentSendIndex,bigData.length);
    
    UInt8 total = 0;
    Byte *bytes = (Byte *)[bigData bytes];
    //下面是Byte 转换为16进制。
    for(int i=0;i<[bigData length];i++)
    {
        total = total+ bytes[i];
    }
    int product = 5;
    int crc = total&0xFF;
    int version = 0x00;
    int count = _ackCount;// 4 8 2
    int index = _currentSendIndex;
    int currentLength = length;
    
    int x = product;
    int xx = crc;
    int c1 = version<<4; int c2 = (count&0x3c00)>>10;
    int xxx = c1|c2;
    
    int c3 = count &0x03fc;
    int xxxx = c3>>2;
    
    int c4 = (count&0x0003)<<6;
    int c5 = (index &0x3F00)>>8;
    int xxxxx = c4|c5;
    int c6 = index&0x00FF;
    int xxxxxx = c6;
    
    int c7 = currentLength &0x03ff;
    int xxxxxxx = c7 >>2;
    
    int c8 = (currentLength &0x0003)<<6;
    
    BOOL err = NO;
    BOOL ack = NO;
    BOOL reserve = NO;
    c8 = bitInsertInt(c8, 4, ack);
    c8 = bitInsertInt(c8, 5, err);
    int xxxxxxxx = c8;
    
    UInt8 headVal[8] = {0};
    headVal[0] = x;
    headVal[1] = xx;
    headVal[2] = xxx;
    headVal[3] = xxxx;
    headVal[4] = xxxxx;
    headVal[5] = xxxxxx;
    headVal[6] = xxxxxxx;
    headVal[7] = xxxxxxxx;
    
    NSData *headData = [[NSData alloc] initWithBytes:headVal length:8];
    //    NSLog(@"headData>>>>%@",headData);
    NSMutableData *allData = [NSMutableData data];
    [allData appendData:headData];
    [allData appendData:bigData];
    //    NSLog(@"要发送的包序号>>>%d 长度>>>%d ",_currentSendIndex,allData.length);
    
    int sendCount = allData.length /20;
    int more = allData.length %20;
    //    NSLog(@"一共包>>>%d 末包长度>>%d",sendCount,more);
    for (int i = 0; i <sendCount; i++) {
        NSData *sendData = [allData subdataWithRange:NSMakeRange(i*20,20)];
        [KK_BLEService senderSpeedDataToPeripheral:sendData];
        //        NSLog(@"发送小包序号>>>[%d 数据长度>>>%d]",i,sendData.length);
        usleep(100);
        if (i == sendCount-1) {
            NSData *sendData = [allData subdataWithRange:NSMakeRange((i+1)*20,more)];
            //            NSLog(@"发送末小包序号>>>[%d 数据长度>>>%d]",i+1,sendData.length);
            [KK_BLEService senderSpeedDataToPeripheral:sendData];
        }
    }
}

- (void)sendGet529WithBlock:(KKBLEAcceptBlock)block
{
    UInt8 val[3] = {0x05, 0x01, 0x1B};
    NSLog(@"获取支持的推送");
    LogWrite(@"获取支持的推送", nil, nil);
    [self sendBytes:val length:3 block:block];
}

@end

